﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Odbc;
using System.IO;

namespace QLCaiMep
{
    public partial class frmThietLap : Form
    {
        #region HAM BIEN TOAN CUC

        public static string Admin = "";
        public static string Ma_nhan_vien = "";
        private string Thu_muc = Using.Get_thu_muc_hinh();
        private DataTable dt_nhanvien = null;
        private DataTable dt_nhomvaitro = null;
        private DataTable dt_xeplich = null;
        private DataTable dt_chamcong = null;
        private BindingManagerBase dhh_nhanvien = null;
        private BindingManagerBase dhh_nhanvien_xemlich = null;
        private SortedList st_tuan = null;
        private SortedList st_thu = null;
        private SortedList st_gio = null;
        private Boolean bReset = false;
        private const int ispace = 40;
        private Size size = new Size(ispace, 36);
        private string manv = "";
        private string donvi = "";

        public frmThietLap()
        {
            InitializeComponent();
        }

        private void frmThietLap_Load(object sender, EventArgs e)
        {
            try
            {
                DsNhanVien();
                DsNhomVaiTro();
                DsNgayTrongTuan();
                DsThuTrongTuan();
                btnXL_Click(sender, e);
            }
            catch (Exception)
            {
            }
        } 

        private void btnHome_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        private void HideAll()
        {
            groupTHXL.Visible = false;
            groupXL.Visible = false;
        }

        private void Ds_XepLich_Tuan(DateTime ngay)
        {
            string sql = "Select * From XepLich Where ngaylam BETWEEN '" + ngay.ToString("yyyyMMdd") + "' AND '" + ngay.AddDays(7).ToString("yyyyMMdd") + "'";
            dt_xeplich = Using.GetQuery(sql);
        }

        private void Ds_XepLich(DateTime ngay)
        {
            string sql = "Select * From XepLich Where ngaylam='" + ngay.ToString("yyyyMMdd") + "'";
            dt_xeplich = Using.GetQuery(sql);
        }

        private void Ds_XepLich(string namthang)
        {
            string sql = "Select * From XepLich Where Left(ngaylam,6)='" + namthang + "'";
            dt_xeplich = Using.GetQuery(sql);
        }

        private void DsChamCong(string namthang)
        {
            string sql = "Select * From ChamCong Where Convert(char(6),giovao,112)='" + namthang + "'";
            dt_chamcong = Using.GetQuery(sql);
        }

        private void DsNhanVien()
        {
            string sql = "Select a.*,b.tenvt From NhanVien a Inner Join NhomVaiTro b On a.vaitro=b.mavt Where a.consudung='true'";
            dt_nhanvien = Using.GetQuery(sql);
        }

        private void DsNhomVaiTro()
        {
            string sql = "Select * From NhomVaiTro Where consudung='true'";
            dt_nhomvaitro = Using.GetQuery(sql);
        }

        private void DsThuTrongTuan()
        {
            st_thu = new SortedList();
            st_thu.Add("Monday", "Thứ Hai");
            st_thu.Add("Tuesday", "Thứ Ba");
            st_thu.Add("Wednesday", "Thứ Tư");
            st_thu.Add("Thursday", "Thứ Năm");
            st_thu.Add("Friday", "Thứ Sáu");
            st_thu.Add("Saturday", "Thứ Bảy");
            st_thu.Add("Sunday", "Chủ Nhật");
        }

        private void DsNgayTrongTuan()
        {
            st_tuan = new SortedList();
            st_tuan.Add("Monday", 2);
            st_tuan.Add("Tuesday", 3);
            st_tuan.Add("Wednesday", 4);
            st_tuan.Add("Thursday", 5);
            st_tuan.Add("Friday", 6);
            st_tuan.Add("Saturday", 7);
            st_tuan.Add("Sunday", 8);
        }

        #region TINH HINH XEP LICH

        private void THXL_DsDonVi()
        {
            if (comTHXL_Nhomvaitro.DataSource == null)
            {
                string sql = "Select * From vitricongtac Where consudung='true' Order By tenvt Asc";
                DataTable dt = Using.GetQuery(sql);
                comTHXL_Nhomvaitro.DataSource = dt;
                comTHXL_Nhomvaitro.DisplayMember = "tenvt";
                comTHXL_Nhomvaitro.ValueMember = "mavt";
            }
        }

        private void THXL_DsNhanVien()
        {
            dhh_nhanvien = BindingContext[dt_nhanvien];
            dhh_nhanvien.PositionChanged += new EventHandler(dhh_nhanvien_PositionChanged);
            gvTHXL_Nhanvien.AutoGenerateColumns = false;
            gvTHXL_Nhanvien.DataSource = dt_nhanvien;
            if (Ma_nhan_vien == manv) dt_nhanvien.DefaultView.RowFilter = "manv='" + manv + "'";
        }

        private void Xuat_thong_tin_nhan_vien()
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_nhanvien.Current;
                manv = drv["manv"].ToString();
                lblTHXL_Hoten.Text = drv["honv"].ToString().Trim() + " " + drv["tennv"].ToString().Trim();
                lblTHXL_Vaitro.Text = drv["tenvt"].ToString();
                try { picTHXL_Hinh.Image = new Bitmap(Thu_muc + drv["hinh"].ToString()); }
                catch { picTHXL_Hinh.Image = null; }
                picTHXL_Hinh.SizeMode = PictureBoxSizeMode.StretchImage;
            }
            catch (Exception)
            {
            }
        }

        private void dhh_nhanvien_PositionChanged(object sender, EventArgs e)
        {
            try
            {
                btnTHXL_Luu.Text = "Lưu thay đổi             ";
                Xuat_thong_tin_nhan_vien();
            }
            catch (Exception)
            {
            }
        }

        private void btnTHXL_Click(object sender, EventArgs e)
        {
            try
            {
                HideAll();
                groupTHXL.Visible = true;
                THXL_DsDonVi();
                THXL_DsNhanVien();
                Xuat_thong_tin_nhan_vien();
                comTHXL_Nhomvaitro_SelectedIndexChanged(sender, e);
                btnTHXL_Tuanhientai_Click(sender, e);
                txtTHXL_Tim.Text = "Tìm nhân viên";
            }
            catch (Exception)
            {
            }
        }

        private DateTime GetMondayOfMonth(DateTime now)
        {
            string thu = now.DayOfWeek.ToString();
            int index = Convert.ToInt32(st_tuan.IndexOfKey(thu));
            index = Convert.ToInt32(st_tuan.GetByIndex(index));
            index -= 2;
            now = now.AddDays(-index);
            return now;
        }

        private void btnTHXL_Tuanhientai_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime now = DateTime.Now;
                string thu = now.DayOfWeek.ToString();
                int index = Convert.ToInt32(st_tuan.IndexOfKey(thu));
                index = Convert.ToInt32(st_tuan.GetByIndex(index));
                index -= 2;
                now = now.AddDays(-index);
                now = now.AddDays(-1);
                comTHXL_Chontuan.Value = now;
            }
            catch (Exception)
            {
            }
        }

        private void THXL_GioBatDau_GioKetThuc(string manv, string ngaylam, TextBox txt1, TextBox txt2, TextBox txt3, TextBox txt4)
        {
            bReset = true;
            txt1.Text = txt2.Text = "";
            txt3.Text = txt4.Text = "";
            bReset = false;
            dt_xeplich.DefaultView.RowFilter = "manv='" + manv + "' AND ngaylam='" + ngaylam + "'";
            if (dt_xeplich.DefaultView.Count >= 1)
            {
                try
                {
                    txt1.Text = dt_xeplich.DefaultView[0]["giobd"].ToString();
                    txt2.Text = dt_xeplich.DefaultView[0]["giokt"].ToString();
                }
                catch { }
                try
                {
                    txt3.Text = dt_xeplich.DefaultView[1]["giobd"].ToString();
                    txt4.Text = dt_xeplich.DefaultView[1]["giokt"].ToString();
                }
                catch { }
                try
                {
                    if (dt_xeplich.DefaultView[0]["ghichu"].ToString() == "")
                        btnTHXL_Luu.Text = "Duyệt                       ";
                    if (dt_xeplich.DefaultView[1]["ghichu"].ToString() == "")
                        btnTHXL_Luu.Text = "Duyệt                       ";
                }
                catch (Exception)
                {
                }
                if (txt1.Text == "0.00") txt1.Text = "";
                if (txt2.Text == "0.00") txt2.Text = "";
                if (txt3.Text == "0.00") txt3.Text = "";
                if (txt4.Text == "0.00") txt4.Text = "";
            }
        }

        private void comTHXL_Chontuan_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                DateTime ngay = comTHXL_Chontuan.Value;

                btnTHXL_Luu.Text = "Lưu thay đổi             ";

                string thu = ngay.DayOfWeek.ToString();

                if (thu != "Monday")
                {
                    int index = Convert.ToInt32(st_tuan.IndexOfKey(thu));
                    index = Convert.ToInt32(st_tuan.GetByIndex(index));
                    index -= 2;
                    ngay = ngay.AddDays(-index);
                    ngay = ngay.AddDays(-1);
                    comTHXL_Chontuan.Value = ngay;
                }

                lblTHXL_Tieude.Text = "LỊCH CÔNG TÁC TUẦN " + ngay.ToString("dd/MM/yyyy") + " - " + ngay.AddDays(6).ToString("dd/MM/yyyy");

                Ds_XepLich_Tuan(ngay);

            }
            catch (Exception)
            {
            }
        }

        private void comTHXL_Nhomvaitro_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                donvi = comTHXL_Nhomvaitro.SelectedValue.ToString();
                dt_nhanvien.DefaultView.RowFilter = "vitri='" + donvi + "'";
                if (Ma_nhan_vien == manv)
                    dt_nhanvien.DefaultView.RowFilter = "manv='" + manv + "'";
                dhh_nhanvien_PositionChanged(sender, e);
            }
            catch (Exception)
            {
            }
        }

        private void txtTHXL_Tim_TextChanged(object sender, EventArgs e)
        {
            try
            {
                string tim = txtTHXL_Tim.Text.Trim();
                string chuoi = "tennv like '*" + tim + "*'";
                dt_nhanvien.DefaultView.RowFilter = chuoi;
                if (dt_nhanvien.DefaultView.Count == 0)
                {
                    chuoi = "diachi like '" + tim + "*'";
                    dt_nhanvien.DefaultView.RowFilter = chuoi;
                    if (dt_nhanvien.DefaultView.Count == 0)
                    {
                        chuoi = "cmnd like '" + tim + "*'";
                        dt_nhanvien.DefaultView.RowFilter = chuoi;
                        if (dt_nhanvien.DefaultView.Count == 0)
                        {
                            chuoi = "dienthoai like '" + tim + "*'";
                            dt_nhanvien.DefaultView.RowFilter = chuoi;
                        }
                    }
                }
                Xuat_thong_tin_nhan_vien();
            }
            catch (Exception)
            {
            }
        }

        private void txtTHXL_Tim_Click(object sender, EventArgs e)
        {
            txtTHXL_Tim.Text = "";
        }

        private void btnTHXL_Saochep_Click(object sender, EventArgs e)
        {
            try
            {
            }
            catch (Exception)
            {
            }
        }

        public DataTable THXL_ReadExcel(string Duong_dan, string fileName)
        {
            try
            {
                OleDbConnection connection = new OleDbConnection();
                connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + Duong_dan); //Excel 97-2003, .xls
                string excelQuery = @"Select * FROM [" + fileName + "$]";
                connection.Open();
                OleDbCommand cmd = new OleDbCommand(excelQuery, connection);
                OleDbDataAdapter adapter = new OleDbDataAdapter();
                adapter.SelectCommand = cmd;
                DataSet ds = new DataSet();
                adapter.Fill(ds);
                DataTable dt = ds.Tables[0];
                connection.Close();
                return dt;
            }
            catch { return null; }
        }

        private void THXL_LoadDuLieuExcel(DataTable dt, int x, TextBox txt1, TextBox txt2, TextBox txt3, TextBox txt4)
        {
            try
            {
                txt1.Text = Convert.ToDouble(dt.Rows[x][1]).ToString("#.#0");
                if (txt1.Text == ".00") txt1.Text = "";

                txt2.Text = Convert.ToDouble(dt.Rows[x][2]).ToString("#.#0");
                if (txt2.Text == ".00") txt2.Text = "";

                txt3.Text = Convert.ToDouble(dt.Rows[x][3]).ToString("#.#0");
                if (txt3.Text == ".00") txt3.Text = "";

                txt4.Text = Convert.ToDouble(dt.Rows[x][4]).ToString("#.#0");
                if (txt4.Text == ".00") txt4.Text = "";

            }
            catch (Exception)
            {
            }
        }

        private void THXL_WriteFileText(DataTable dt)
        {
            try
            {
                FileStream aFile = new FileStream("ThietLap.txt", FileMode.OpenOrCreate);
                StreamWriter sw = new StreamWriter(aFile);
                if (dt != null && dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            sw.Write("{0,-10}",row[i].ToString());
                        }
                        sw.WriteLine();
                    }
                    sw.Close();
                }
            }
            catch (IOException)
            {
                
            }
        }

        private void THXL_SaveToDB(DataTable dt)
        {
            try
            {
                DateTime startDate = comTHXL_Chontuan.Value;
                string EidTemp = null;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DateTime dateTemp = startDate;
                    if (EidTemp != dt.Rows[i][0].ToString() && dt.Rows[i][0].ToString() != string.Empty)
                        EidTemp = dt.Rows[i][0].ToString();                    
                    
                    for (int j = 1; j < dt.Columns.Count; j++)
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            string sql = string.Format("insert into XepLich values('{0}','{1}','{2}','{3}')"
                                , EidTemp, dateTemp.ToString("yyyyMMdd"), dt.Rows[i][j].ToString(), "");
                            Using.Proccess(sql);
                        }
                        dateTemp = dateTemp.AddDays(1);
                    }
                }
            }
            catch (Exception ex)
            { 
            }
        }
        
        private void btnTHXL_Import_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog file = new OpenFileDialog();
                file.Filter = "Các tập tin *.xls | *.xls";
                if (file.ShowDialog() == DialogResult.OK)
                {
                    DataTable dtExcel = THXL_ReadExcel(file.FileName, file.SafeFileName.Substring(0, file.SafeFileName.Length - 4));
                    THXL_SaveToDB(dtExcel);
                }
            }
            catch (Exception)
            {
            }
        }

        private void THXL_XelLichNhanVien(string ngaylam, string manv, string txt1, string txt2, string txt3, string txt4)
        {
            try
            {
                dt_xeplich.DefaultView.RowFilter = "manv='" + manv + "' AND ngaylam='" + ngaylam + "'";

                if (txt1 == "") txt1 = "0";
                if (txt2 == "") txt2 = "0";
                if (txt3 == "") txt3 = "0";
                if (txt4 == "") txt4 = "0";

                string sql = string.Format("Insert Into XepLich(manv,ngaylam,maca,giobd,giokt,ghichu)Values('{0}','{1}','{2}','{3}','{4}','Ad')", manv, ngaylam, "1", txt1, txt2);
                if (dt_xeplich.DefaultView.Count >= 1)
                    sql = string.Format(@"Update XepLich Set giobd='{0}',giokt='{1}',ghichu='Ad' Where manv='{2}' AND ngaylam='{3}' AND maca='1'", txt1, txt2, manv, ngaylam);

                Using.Proccess(sql);

                sql = string.Format("Insert Into XepLich(manv,ngaylam,maca,giobd,giokt,ghichu)Values('{0}','{1}','{2}','{3}','{4}','Ad')", manv, ngaylam, "2", txt3, txt4);
                if (dt_xeplich.DefaultView.Count >= 1)
                    sql = string.Format(@"Update XepLich Set giobd='{0}',giokt='{1}',ghichu='Ad' Where manv='{2}' AND ngaylam='{3}' AND maca='2'", txt3, txt4, manv, ngaylam);

                Using.Proccess(sql);
            }
            catch { }
        }

        private void btnTHXL_Luu_Click(object sender, EventArgs e)
        {
            try
            {
            }
            catch (Exception)
            {
            }
        }

        private string THXL_TongGioNgay(string txt1, string txt2, string txt3, string txt4)
        {
            string kq = "";
            try
            {
                int phut1, phut2;
                int gio = 0;
                try
                {
                    phut1 = Using.ChuyenGioSangPhut(txt1);
                    phut2 = Using.ChuyenGioSangPhut(txt2);
                    if (phut2 > phut1)
                    {
                        gio += phut2 - phut1;
                        kq = gio / 60 + "." + gio % 60;
                        if (gio % 60 == 0) kq += "0";
                    }
                }
                catch { }
                try
                {
                    phut1 = Using.ChuyenGioSangPhut(txt3);
                    phut2 = Using.ChuyenGioSangPhut(txt4);
                    if (phut2 > phut1)
                    {
                        gio += phut2 - phut1;
                        kq = gio / 60 + "." + gio % 60;
                        if (gio % 60 == 0) kq += "0";
                    }
                }
                catch { }
            }
            catch { }
            return kq;
        }

        private string THXL_TongGioTuan(string txt1, string txt2, string txt3, string txt4, string txt5, string txt6, string txt7)
        {
            string kq = "";
            try
            {
                int phut = 0;
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt1);
                }
                catch { }
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt2);
                }
                catch { }
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt3);
                }
                catch { }
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt4);
                }
                catch { }
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt5);
                }
                catch { }
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt6);
                }
                catch { }
                try
                {
                    phut += Using.ChuyenGioSangPhut(txt7);
                }
                catch { }
                kq = phut / 60 + "." + phut % 60;
                if (phut % 60 == 0) kq += "0";
            }
            catch { }
            return kq;
        }

        private void txt12_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt13_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt14_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt15_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt16_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt17_TextChanged(object sender, EventArgs e)
        {

        }

        private void txt18_TextChanged(object sender, EventArgs e)
        {

        }

        private void gvTHXL_Nhanvien_DoubleClick(object sender, EventArgs e)
        {
            //Ma_nhan_vien = manv;
            //btnXL_Click(sender, e);
        }

        #endregion

        #region XEM LICH

        private void XL_DsDonVi()
        {
            if (comXL_Nhomvaitro.DataSource == null)
            {
                string sql = "Select * From vitricongtac Where consudung='true' Order By tenvt Asc";
                DataTable dt = Using.GetQuery(sql);
                DataRow row = dt.NewRow();
                row["mavt"] = 0;
                row["tenvt"] = "Tất cả";
                row["consudung"] = true;
                dt.Rows.Add(row);
                comXL_Nhomvaitro.DataSource = dt;
                comXL_Nhomvaitro.DisplayMember = "tenvt";
                comXL_Nhomvaitro.ValueMember = "mavt";
            }
        }

        private void btnXL_Click(object sender, EventArgs e)
        {
            try
            {
                HideAll();
                groupXL.Visible = true;
                rbtnXL_Chonthang.Checked = true;
                groupXL_Chonthang.Visible = true;
                groupXL_Chonngay.Visible = false;
                XL_DsDonVi();
                Ds_XepLich(comXL_Chonthang.Value.ToString("yyyyMM"));
                comXL_Nhomvaitro_SelectedIndexChanged(sender, e);
                Ma_nhan_vien = "";
            }
            catch (Exception)
            {
            }
        }

        private void rbtnXL_Chonthang_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnXL_Chonthang.Checked)
            {
                groupXL_Chonthang.Visible = true;
                groupXL_Chonngay.Visible = false;
                Ds_XepLich(comXL_Chonthang.Value.ToString("yyyyMM"));
                comXL_Nhomvaitro_SelectedIndexChanged(sender, e);
            }
            else
            {
                groupXL_Chonthang.Visible = false;
                groupXL_Chonngay.Visible = true;
                dt_xeplich.DefaultView.RowFilter = "ngaylam='" + comXLNgay_Chonngay.Value.ToString("yyyyMMdd") + "'";
                XLNgay_TaoGioDuKien();
                XLNgay_DsDonVi();
                comXLNgay_Nhomvaitro_SelectedIndexChanged(sender, e);
            }
        }

        private void btnXL_Thanghientai_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime now = DateTime.Now;
                now = new DateTime(now.Year, now.Month, 1);
                comXL_Chonthang.Value = now;
            }
            catch (Exception)
            {
            }
        }

        private void comXL_Chonthang_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                Ds_XepLich(comXL_Chonthang.Value.ToString("yyyyMM"));
                comXL_Nhomvaitro_SelectedIndexChanged(sender, e);
            }
            catch (Exception)
            {
            }
        }

        private DataTable XL_TaoBangNhanVien()
        {
            DataTable dt = new DataTable();
            DataColumn dc;
            //manv
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "manv";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            //ho ten
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "hoten";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            //tuan1
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "tuan1";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            //tuan2
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "tuan2";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            //tuan3
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "tuan3";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            //tuan4
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "tuan4";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            //tuan5
            dc = new DataColumn();
            dc.DataType = System.Type.GetType("System.String");
            dc.ColumnName = "tuan5";
            dc.Caption = "";
            dc.AutoIncrement = false;
            dt.Columns.Add(dc);
            /***/
            return dt;
        }

        private void XL_FillData(DataView view)
        {
            try
            {
                DataTable dtNhanVien = XL_TaoBangNhanVien();
                DateTime dateBegin = comXL_Chonthang.Value;
                dateBegin = new DateTime(dateBegin.Year, dateBegin.Month, 1);
                dateBegin = GetMondayOfMonth(dateBegin);
                DateTime dateEnd = dateBegin;
                DateTime dateBeginTemp, dateEndTemp;

                DataRow row = dtNhanVien.NewRow();
                row[0] = ""; row[1] = "";

                dateBeginTemp = dateBegin;
                dateEndTemp = AddOfWeek(dateBegin);
                row[2] = dateBeginTemp.ToString("dd/MM") + " - " + dateEndTemp.AddDays(-1).ToString("dd/MM");

                dateBeginTemp = dateEndTemp;
                dateEndTemp = AddOfWeek(dateEndTemp);
                row[3] = dateBeginTemp.ToString("dd/MM") + " - " + dateEndTemp.AddDays(-1).ToString("dd/MM");

                dateBeginTemp = dateEndTemp;
                dateEndTemp = AddOfWeek(dateEndTemp);
                row[4] = dateBeginTemp.ToString("dd/MM") + " - " + dateEndTemp.AddDays(-1).ToString("dd/MM");

                dateBeginTemp = dateEndTemp;
                dateEndTemp = AddOfWeek(dateEndTemp);
                row[5] = dateBeginTemp.ToString("dd/MM") + " - " + dateEndTemp.AddDays(-1).ToString("dd/MM");

                dateBeginTemp = dateEndTemp;
                dateEndTemp = AddOfWeek(dateEndTemp);
                row[6] = dateBeginTemp.ToString("dd/MM") + " - " + dateEndTemp.AddDays(-1).ToString("dd/MM");

                dateEnd = dateEndTemp;

                dtNhanVien.Rows.Add(row);

                int songay = (int)(dateEnd - dateBegin).TotalDays;

                for (int i = 0; i < view.Count; i++)
                {
                    dateBeginTemp = dateBegin;
                    string manv = view[i]["manv"].ToString();
                    string chuoi = "";
                    row = dtNhanVien.NewRow();
                    row[0] = manv;
                    row[2] = row[3] = row[4] = row[5] = "";
                    row[1] = view[i]["honv"] + " " + view[i]["tennv"];
                    for (int j = 2; j <= 6; j++)
                    {
                        chuoi = "manv='" + manv + "' AND ngaylam >= '" + dateBeginTemp.ToString("yyyyMMdd") + "' AND ngaylam <= '" + dateBeginTemp.AddDays(6).ToString("yyyyMMdd") + "' AND ghichu='Ad'";
                        dt_xeplich.DefaultView.RowFilter = chuoi;
                        if (dt_xeplich.DefaultView.Count >= 1)
                            row[j] = "X";
                        dateBeginTemp = dateBeginTemp.AddDays(7);
                    }
                    dtNhanVien.Rows.Add(row);
                }
                dhh_nhanvien_xemlich = BindingContext[dtNhanVien];
                dhh_nhanvien_xemlich.PositionChanged += new EventHandler(dhh_nhanvien_xemlich_PositionChanged);
                gvXL_Vaitro.AutoGenerateColumns = false;
                gvXL_Vaitro.DataSource = dtNhanVien;
            }
            catch (Exception)
            {
            }
        }

        private void dhh_nhanvien_xemlich_PositionChanged(object sender, EventArgs e)
        {
            try
            {
                DataRowView drv = (DataRowView)dhh_nhanvien_xemlich.Current;
                manv = drv["manv"].ToString();
            }
            catch (Exception)
            {
            }
        }

        private void comXL_Nhomvaitro_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int donvi = Convert.ToInt32(comXL_Nhomvaitro.SelectedValue);
                gvXL_Vaitro.DataSource = null;
                lblXL_Tieude.Text = "TÌNH HÌNH XẾP LỊCH THÁNG " + comXL_Chonthang.Value.ToString("MM/yyyy") + Environment.NewLine + comXL_Nhomvaitro.Text.ToUpper();
                if (donvi == 0)
                    dt_nhanvien.DefaultView.RowFilter = "1=1";
                else
                    dt_nhanvien.DefaultView.RowFilter = "vitri='" + donvi + "'";
                if (dt_nhanvien.DefaultView.Count == 0) return;
                XL_FillData(dt_nhanvien.DefaultView);
            }
            catch (Exception)
            {
            }
        }

        private void XLNgay_VeLabelGio(GroupBox khung, Point point, Size size, string text)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Location = point;
            lbl.Size = size;
            lbl.Text = text;
            lbl.TextAlign = ContentAlignment.MiddleCenter;
            lbl.BackColor = Color.Transparent;
            khung.Controls.Add(lbl);
        }

        private void XLNgay_DsDonVi()
        {
            if (comXLNgay_Nhomvaitro.DataSource == null)
            {
                string sql = "Select * From vitricongtac Where consudung='true' Order By tenvt Asc";
                DataTable dt = Using.GetQuery(sql);
                DataRow row = dt.NewRow();
                row["mavt"] = 0;
                row["tenvt"] = "Tất cả";
                row["consudung"] = true;
                dt.Rows.Add(row);
                comXLNgay_Nhomvaitro.DataSource = dt;
                comXLNgay_Nhomvaitro.DisplayMember = "tenvt";
                comXLNgay_Nhomvaitro.ValueMember = "mavt";
            }
        }

        private void XLNgay_TaoGioDuKien()
        {
            if (st_gio == null)
            {
                st_gio = new SortedList();
                int index = 7;
                Point point = new Point(217, 84);
                for (int i = 0; i < 13; i++)
                {
                    point = new Point(217 + i * size.Width, 84);
                    st_gio.Add(index, point.X);
                    XLNgay_VeLabelGio(groupXL_Chonngay, point, size, index.ToString());
                    index++;
                }
            }
        }

        private void btnXLNgay_Ngayhientai_Click(object sender, EventArgs e)
        {
            comXLNgay_Chonngay.Value = DateTime.Now;
        }

        private void btnXLNgay_Ngaytruoc_Click(object sender, EventArgs e)
        {
            DateTime now = comXLNgay_Chonngay.Value;
            now = now.AddDays(-1);
            comXLNgay_Chonngay.Value = now;
        }

        private void btnXLNgay_Ngaysau_Click(object sender, EventArgs e)
        {
            DateTime now = comXLNgay_Chonngay.Value;
            now = now.AddDays(1);
            comXLNgay_Chonngay.Value = now;
        }

        private void comXLNgay_Chonngay_ValueChanged(object sender, EventArgs e)
        {
            comXLNgay_Nhomvaitro_SelectedIndexChanged(sender, e);
        }

        private void XLNgay_VeGioLamViec(Point p1, Point p2, Panel khung, Color mau)
        {
            Label lbl = new Label();
            lbl.AutoSize = false;
            lbl.Location = new Point(p1.X, p1.Y);
            lbl.Size = new Size(p2.X - p1.X, 20);
            lbl.BackColor = mau;
            khung.Controls.Add(lbl);
        }

        private Point XLNgay_ViTriGioLam(string fgiovao)
        {
            Point point = new Point(0, 0);
            int gio_vt, phut_vt;
            int igio = 0;
            gio_vt = fgiovao.IndexOf('.');
            if (gio_vt >= 1)
            {
                phut_vt = Convert.ToInt32(fgiovao.Substring(gio_vt + 1, 1));
                gio_vt = Convert.ToInt32(fgiovao.Substring(0, gio_vt));
            }
            else
            {
                gio_vt = Convert.ToInt32(fgiovao);
                phut_vt = 0;
            }
            if (gio_vt >= 7 && gio_vt <= 19)
            {
                igio = Convert.ToInt32(st_gio.IndexOfKey(gio_vt));
                igio = Convert.ToInt32(st_gio.GetByIndex(igio));
                igio = CTCN_ViTriGioLam(phut_vt, igio, gio_vt);
                point = new Point(igio, 92);
            }
            else
            {
                if (gio_vt < 7)
                {
                    igio = Convert.ToInt32(st_gio.IndexOfKey(7));
                    igio = Convert.ToInt32(st_gio.GetByIndex(igio));
                    point = new Point(igio - ispace / 4, 92);
                }
                else
                {
                    igio = Convert.ToInt32(st_gio.IndexOfKey(19));
                    igio = Convert.ToInt32(st_gio.GetByIndex(igio));
                    point = new Point(igio + ispace / 4, 92);
                }
            }
            return point;
        }

        private int CTCN_ViTriGioLam(int phut, int igio, int gio_vt)
        {
            int kq = 0;
            if (phut >= 5)
            {
                kq = igio + ispace / 2 + ispace / 4;
            }
            else
            {
                if (phut == 0)
                {
                    kq = igio;
                }
                else
                {
                    kq = igio + ispace / 4;
                    if (phut >= 3) kq = igio + ispace / 2;
                }
            }
            kq -= 3;
            if (gio_vt < 10) kq -= 2;
            return kq;
        }

        private void XLNgay_DrawLine(Point p1, Point p2, Panel khung)
        {
            Label lbl = new Label();
            lbl.Location = p1;
            lbl.Size = new Size(1, p2.Y - p1.Y);
            lbl.Text = "";
            lbl.AutoSize = false;
            lbl.BackColor = Color.Black;
            khung.Controls.Add(lbl);
        }

        private void XLNgay_XemLichLamViec(DataView view, DateTime ngay)
        {
            string manv = "", hinh = "";
            Point point1, point2;
            Point p1, p2;
            Size size_hinh = new Size(100, 120);
            Bitmap bmp = null;
            for (int i = 0; i < view.Count; i++)
            {
                manv = view[i]["manv"].ToString();
                hinh = view[i]["hinh"].ToString();
                try { bmp = new Bitmap(Thu_muc + hinh); }
                catch { bmp = new Bitmap(global::QLCaiMep.Properties.Resources.x); }
                //Ve hinh nhan vien
                PictureBox pic = new PictureBox();
                pic.Location = new Point(0, size_hinh.Height * i);
                pic.Size = size_hinh;
                pic.Image = bmp;
                pic.SizeMode = PictureBoxSizeMode.StretchImage;
                khungXLNgay.Controls.Add(pic);
                //Ve gio ke hoach lam viec
                dt_xeplich.DefaultView.RowFilter = "manv='" + manv + "' AND ngaylam='" + ngay.ToString("yyyyMMdd") + "'";
                for (int j = 0; j < dt_xeplich.DefaultView.Count; j++)
                {
                    string giovao = dt_xeplich.DefaultView[j]["giobd"].ToString();
                    string giora = dt_xeplich.DefaultView[j]["giokt"].ToString();
                    point1 = XLNgay_ViTriGioLam(giovao);
                    point2 = XLNgay_ViTriGioLam(giora);
                    point1 = new Point(point1.X - 2, size_hinh.Height * i + size_hinh.Height / 2 - 10);
                    point2 = new Point(point2.X - 2, size_hinh.Height * i + size_hinh.Height / 2 - 10);
                    XLNgay_VeGioLamViec(point1, point2, khungXLNgay, Color.Brown);
                    p1 = new Point(point1.X, 0);
                    p2 = new Point(point1.X, point1.Y);
                    XLNgay_DrawLine(p1, p2, khungXLNgay);
                    p1 = new Point(point2.X, 0);
                    p2 = new Point(point2.X, point2.Y);
                    XLNgay_DrawLine(p1, p2, khungXLNgay);
                }
            }
        }

        private void comXLNgay_Nhomvaitro_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int donvi = Convert.ToInt32(comXLNgay_Nhomvaitro.SelectedValue);
                khungXLNgay.Visible = false;
                khungXLNgay.Controls.Clear();
                khungXLNgay.Visible = true;
                string thu = comXLNgay_Chonngay.Value.DayOfWeek.ToString();
                try
                {
                    int x = Convert.ToInt32(st_thu.IndexOfKey(thu));
                    thu = st_thu.GetByIndex(x).ToString();
                }
                catch { }

                lblXLNgay_Tieude.Text = "XEM LỊCH NGÀY " + thu + " " + comXLNgay_Chonngay.Value.ToString("dd/MM/yyyy") + Environment.NewLine + comXLNgay_Nhomvaitro.Text.ToUpper();
                if (donvi == 0) 
                    dt_nhanvien.DefaultView.RowFilter = "1=1";
                else
                    dt_nhanvien.DefaultView.RowFilter = "vitri='" + donvi + "'";
                if (Ma_nhan_vien != "")
                    dt_nhanvien.DefaultView.RowFilter = "manv='" + manv + "'";
                if (dt_nhanvien.DefaultView.Count == 0) return;
                XLNgay_XemLichLamViec(dt_nhanvien.DefaultView, comXLNgay_Chonngay.Value);
            }
            catch (Exception)
            {
            }
        }

        private void gvXL_Vaitro_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                Ma_nhan_vien = manv;
                btnTHXL_Click(sender, e);
            }
            catch (Exception)
            {
            }
        }

        #endregion

        private DateTime AddOfWeek(DateTime now)
        {
            string thu = now.DayOfWeek.ToString();
            int index = Convert.ToInt32(st_tuan.IndexOfKey(thu));
            index = Convert.ToInt32(st_tuan.GetByIndex(index));
            index -= 2;
            now = now.AddDays(-index);
            now = now.AddDays(7);
            return now;
        }

        private void btnTHXL_Tuantruoc_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime now = comTHXL_Chontuan.Value;
                string thu = now.DayOfWeek.ToString();
                int index = Convert.ToInt32(st_tuan.IndexOfKey(thu));
                index = Convert.ToInt32(st_tuan.GetByIndex(index));
                index -= 2;
                now = now.AddDays(-index);
                now = now.AddDays(-7);
                now = now.AddDays(-1);
                comTHXL_Chontuan.Value = now;
            }
            catch (Exception)
            {
            }
        }

        private void btnTHXL_Tuansau_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime now = comTHXL_Chontuan.Value;
                string thu = now.DayOfWeek.ToString();
                int index = Convert.ToInt32(st_tuan.IndexOfKey(thu));
                index = Convert.ToInt32(st_tuan.GetByIndex(index));
                index -= 2;
                now = now.AddDays(-index);
                now = now.AddDays(7);
                now = now.AddDays(-1);
                comTHXL_Chontuan.Value = now;
            }
            catch (Exception)
            {
            }
        }

        private void btnXL_Thangtruoc_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime now = comXL_Chonthang.Value;
                now = new DateTime(now.Year, now.Month, 1);
                now = now.AddMonths(-1);
                comXL_Chonthang.Value = now;
            }
            catch (Exception)
            {
            }
        }

        private void btnXL_Thangsau_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime now = comXL_Chonthang.Value;
                now = new DateTime(now.Year, now.Month, 1);
                now = now.AddMonths(1);
                comXL_Chonthang.Value = now;
            }
            catch (Exception)
            {
            }
        }

        private void Copy_ngay_hom_truoc(TextBox txt1, TextBox txt2, TextBox txt3, TextBox txt4, string s1, string s2, string s3, string s4)
        {
            txt1.Text = s1;
            txt2.Text = s2;
            txt3.Text = s3;
            txt4.Text = s4;
        }

        private void Clear_ngay_hien_tai(TextBox txt1, TextBox txt2, TextBox txt3, TextBox txt4)
        {
            txt1.Text = "";
            txt2.Text = "";
            txt3.Text = "";
            txt4.Text = "";
        }

    }
}
